import { TOKEN } from "@/constants"
import { start, close } from "../utils/nprogress.js"
import { createRouter, createWebHistory } from "vue-router"
import type { RouteRecordRaw } from "vue-router"

export const routes: RouteRecordRaw[] = [
  {
    path: "/",
    name: "home",
    component: () => import("@/views/home/HomeView.vue"),
    meta: {
      authentication: true
    },
    children: []
  },
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/login/LoginPage.vue"),
    meta: {
      authentication: false
    }
  },
  { path: "/:pathMatch(.*)*", name: "NotFound", component: () => import("@/views/not-found/NotFound.vue") }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
})

router.beforeEach((to, _, next) => {
  const token = localStorage.getItem(TOKEN)
  if (!token && to.meta.authentication) {
    next("/login")
  }

  start()
  next()
})

router.afterEach(() => {
  close()
})

export default router
